/*
 * returns an object for jQuery's autocomplete
 * useage: $input.autocomplete({url : http://example.com});
 * require: jQuery, jQuery.rStorage
*/
laksmi.autocompletefactory = function(options){

	var $ = jQuery;

	var settings = $.extend({
			resultCount : 5,		//this is the limit parameter for cake find all method
			minLength : 2,
			}, options);
	
	if (!settings.url) {
		throw new Error("autocompelete factory called without url parameter");
		return null;
	}
	
	var now = new Date();
	//invalidate cache if it is older than 12 hours
	if ($.localStorage('laksmi.cacheTime') && $.localStorage('laksmi.cacheTime') < (now - 1000*60*60*12)) {
		$.localStorage.remove('laksmi.cache');
	}
	$.localStorage('laksmi', {'cacheTime' : now.getTime()});
	
	return {
		resultCount : settings.resultCount,		//this is the limit parameter for cake find all method
		minLength : settings.minLength,
		
		//order of callback calls: create, search, source, GET, response, open, focus, select, close, change
		
		source: function(request, response) {	//the data to use
			var term = request.term;
			if($.localStorage('laksmi.cache') && (settings.url + ':' +  term) in $.localStorage('laksmi.cache') ) {		//if the query is already in the cache
				response($.localStorage('laksmi.cache')[settings.url + ':' +  term]);
				return;
			}
			$.getJSON(settings.url, request, function( data, status, xhr ) {	//if there is no cached version
				var d = {}
				d[settings.url + ':' + request.term] = data;
//TODO: add year and company to the cache
				$.localStorage('laksmi', {'cache' : d});					//add to the cache
				response(data);
			});
		},
		focus : function(event, ui){		//callback for focus on an elem
			var $input = $(this);
			$input.val(ui.item.label);
			$input.data('selectedId', ui.item.value);
			event.preventDefault();
		},
		select : function(event, ui){		//callback for select from the drop down
			var $input = $(this);
			$input.val(ui.item.label);
			$input.data('selectedId', ui.item.value);
			event.preventDefault();
		}
	}
};

/*
http://stackoverflow.com/questions/1268531/jquery-autocomplete-view-all-on-click

$('#myButton').click(function() {
   $('#autocomplete').trigger("focus"); //or "click", at least one should work
});
*/